﻿using DevExpress.XtraEditors.Controls;
using EkStudio.com.bean.xml.BillModule;
using EkStudio.com.bean.xml.BillMultiple;
using EkStudio.com.bean.xml.reflection.JAXB;
using EkStudio.com.bean.xml.RootInterface;
using EkStudio.com.bean.xml.RootInterface.DataSource;
using EkStudio.com.bean.xml.RootInterface.Field;
using EkStudio.com.common.unit;
using EkStudio.com.ui.unitbill.property.Event;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;

namespace EkStudio.com.ui.form.Auto
{
    public partial class AutoQueryFormula : DevExpress.XtraEditors.XtraForm
    {

        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(AutoQueryFormula));

        private ProjectRootPanel RootPanel = null;

        private bool connect = false;

        private string loadBillName = "";//当前加载的模块key

        private int loadBillType = -1;//当前加载的模块类型

        /// <summary>
        /// 条件数据源
        /// </summary>
        private DataTable JoinData = null;
        /// <summary>
        /// 表数据源
        /// </summary>
        private DataTable TableData = null;
        /// <summary>
        /// 条件数据源
        /// </summary>
        private DataTable reqData = null;
        /// <summary>
        /// 输出表格数据源
        /// </summary>
        private DataTable outData = null;

        private BillFormatModule module = null;//当前模块

        private List<BillFormatModule> loadMod = new List<BillFormatModule>();//已加载的模块列表

        private List<SelectItem> TargetSelect = new List<SelectItem>();//已选择的表列表

        private List<SelectItem> JoinSelect = new List<SelectItem>();//外联选择的表列表

        private List<OutFieldData> outList = new List<OutFieldData>();//输出字段集

        private List<OutFieldData> SelfList = new List<OutFieldData>();//当前模块字段集

        private string sqlContent = "";


        private delegate void UpdateStatusDelegate(string key, string xml);

        public AutoQueryFormula(BillFormatModule mod, ProjectRootPanel root)
        {
            InitializeComponent();
            this.module = mod;
            this.RootPanel = root;
            this.InitForm();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void InitForm()
        {

            //选择表数据源
            TableData = new DataTable("TableName");
            TableData.Columns.Add("TabNameCol", typeof(string));//表结构caption
            TableData.Columns.Add("TabRoleCol", typeof(bool));//是否启用权限
            TableData.Columns.Add("TabSourceKey", typeof(string));//key
            TableData.Columns.Add("TabGroupValue", typeof(SelectItem));//模块
            //外联表数据源
            JoinData = new DataTable("TableName");
            JoinData.Columns.Add("FieldWillJoinTable", typeof(string));//被链接表caption
            JoinData.Columns.Add("FieldJoinType", typeof(string));//链接方式
            JoinData.Columns.Add("FieldJoinTable", typeof(string));//连接的表caption
            JoinData.Columns.Add("FieldJoinObject", typeof(SelectJoinItem));//保存的联类
            //参数取值表数据源
            reqData = new DataTable("TableName");
            reqData.Columns.Add("FieldParamKey", typeof(string));//条件变量
            reqData.Columns.Add("FieldReqCaption", typeof(string));//链接字段Caption
            reqData.Columns.Add("FieldReqValue", typeof(string));//链接的Column

            //输出字段数据源
            outData = new DataTable("TableName");
            outData.Columns.Add("ColFieldName", typeof(OutFieldData));//输出字段caption
            outData.Columns.Add("ColWriteField", typeof(OutFieldData));//输出到界面的字段caption
            outData.Columns.Add("ColVisible", typeof(bool));//是否显示
            outData.Columns.Add("ColFieldWidth", typeof(int));//字段宽度
            outData.Columns.Add("ColCommand", typeof(string));//操作命令
            outData.Columns.Add("ColShowSearch", typeof(bool));//是否显示与查询

            GridTabControl.DataSource = TableData;
            GridJoinControl.DataSource = JoinData;
            GridReqControl.DataSource = reqData;
            GridOutContral.DataSource = outData;

            ParamListBox.Items.Clear();
            //加载当前模块
            if (this.module is BillModuleItem || module is BillMultipleItem)//当前是模块
            {
                //主表
                ImageListBoxItem item = new ImageListBoxItem(module.getKey(), "当前模块", 4);
                ParamListBox.Items.Add(item);
                if (module.UiField != null && module.UiField.FieldsProperties != null && module.UiField.FieldsProperties.Count > 0)
                {
                    List<OutFieldData> main = new List<OutFieldData>();
                    List<OutFieldData> sub = new List<OutFieldData>();
                    for (int i = 0; i < module.UiField.FieldsProperties.Count; i++)
                    {
                        BillUiGroupItems group = module.UiField.FieldsProperties[i];
                        if (group.Table)
                        {
                            item = new ImageListBoxItem(module.getKey(), string.Format("当前模块.{0}", group.Caption), 4);
                            ParamListBox.Items.Add(item);
                            if (group.Fields != null && group.Fields.Count > 0)
                            {
                                foreach(BillUiFieldsItem field in group.Fields)
                                {
                                    sub.Add(new OutFieldData(field.Key, field.Key, string.Format("{0}.{1}.{2}", module.getCaption(),group.Caption,field.Caption), field.LanguageTexts,field.Caption));
                                }
                            }
                        }
                        else
                        {
                            foreach (BillUiFieldsItem field in group.Fields)
                            {
                                main.Add(new OutFieldData(field.Key, field.Key, string.Format("{0}.{1}", module.getCaption(),field.Caption), field.LanguageTexts,field.Caption));
                            }
                        }
                    }
                    if (main.Count > 0)
                    {
                        foreach(OutFieldData field in main)
                        {
                            RepositoryOutWriteEdit.Items.Add(field);
                            SelfList.Add(field);
                        }
                    }
                    if (sub.Count > 0)
                    {
                        foreach(OutFieldData field in sub)
                        {
                            RepositoryOutWriteEdit.Items.Add(field);
                            SelfList.Add(field);
                        }
                    }

                    
                }
            }
            
        }
        /// <summary>
        /// 生成被Join表的可选数据
        /// </summary>
        private void LoadWillJoinGridData()
        {
            this.RepositoryJoinWillListEdit.Items.Clear();
            if (TargetSelect.Count > 0)
            {
                foreach (SelectItem Sel in TargetSelect)
                {
                    this.RepositoryJoinWillListEdit.Items.Add(Sel.Caption);
                }
            }
        }

        /// <summary>
        /// 生成Join表的可先数据
        /// </summary>
        private void LoadJoinGirdData()
        {
            this.RepositoryJoinListEdit.Items.Clear();
            if (loadMod.Count > 0)
            {
                foreach (BillFormatModule lt in loadMod)
                {
                    bool exist = false;
                    //判断已先模块中是否已经存在
                    if (TargetSelect.Count > 0)
                    {
                        foreach (SelectItem Sel in TargetSelect)
                        {
                            if (Sel.Bill == lt)
                            {
                                exist = true;
                                break;
                            }
                        }
                    }
                    if (!exist)
                    {
                        this.RepositoryJoinListEdit.Items.Add(lt.getCaption());
                        if (lt.DataSource != null && lt.DataSource.TableItems != null && lt.DataSource.TableItems.Count > 0)
                        {
                            foreach (BillSourceTabItems dtab in lt.DataSource.TableItems)
                            {
                                if (dtab.Key != "0")
                                    this.RepositoryJoinListEdit.Items.Add(dtab.Caption);
                            }
                        }

                    }

                }
            }
        }

        /// <summary>
        /// 自动生成输出字段key
        /// </summary>
        private void LoadOutFieldListData()
        {
            outList.Clear();
            if (TargetSelect.Count > 0)
            {
                foreach (SelectItem table in TargetSelect)
                {
                    //添加当前字段
                    if (table.Value != null && table.Value.Fields != null && table.Value.Fields.Count > 0)
                    {
                        if (table.MainTable)
                        {
                            this.AddOutFieldKey("record_id",string.Format("{0}.{1}",table.TableName,"record_id"), string.Format("{0}.{1}", table.Value.Caption, "record_id"), "","");
                            this.AddOutFieldKey("user_id", string.Format("{0}.{1}", table.TableName, "user_id"), string.Format("{0}.{1}", table.Value.Caption, "user_id"), "","");
                            this.AddOutFieldKey("status", string.Format("{0}.{1}", table.TableName, "status"), string.Format("{0}.{1}", table.Value.Caption, "status"), "","");
                        }
                        else
                        {
                            this.AddOutFieldKey("record_id", string.Format("{0}.{1}", table.TableName, "record_id"), string.Format("{0}.{1}", table.Value.Caption, "record_id"), "","");
                            this.AddOutFieldKey("parent_id", string.Format("{0}.{1}", table.TableName, "parent_id"), string.Format("{0}.{1}", table.Value.Caption, "parent_id"), "","");
                            this.AddOutFieldKey("sort_id", string.Format("{0}.{1}", table.TableName, "sort_id"), string.Format("{0}.{1}", table.Value.Caption, "sort_id"), "", "");
                            this.AddOutFieldKey("status", string.Format("{0}.{1}", table.TableName, "status"), string.Format("{0}.{1}", table.Value.Caption, "status"), "","");
                        }
                        foreach (BillSourceFields field in table.Value.Fields)
                        {

                            this.AddOutFieldKey(field.Key,string.Format("{0}.{1}",table.TableName,field.Key), string.Format("{0}.{1}", table.Value.Caption, field.Caption), field.LanguageTexts,field.Caption);
                        }
                    }
                    //查看当前外联的表
                    if (table.JoinList != null && table.JoinList.Count > 0)
                    {
                        foreach (SelectJoinItem jIt in table.JoinList)
                        {
                            if (jIt.JoinTable != null)
                            {
                                if (jIt.JoinTable.Value != null && jIt.JoinTable.Value.Fields != null && jIt.JoinTable.Value.Fields.Count > 0)
                                {
                                    if (jIt.JoinTable.MainTable)
                                    {
                                        this.AddOutFieldKey("record_id",string.Format("{0}.{1}",jIt.JoinTable.TableName, "record_id"), string.Format("{0}.{1}", jIt.JoinTable.Value.Caption, "record_id"), "","");
                                        this.AddOutFieldKey("user_id", string.Format("{0}.{1}", jIt.JoinTable.TableName, "user_id"), string.Format("{0}.{1}", jIt.JoinTable.Value.Caption, "user_id"), "","");
                                        this.AddOutFieldKey("status", string.Format("{0}.{1}", jIt.JoinTable.TableName, "status"), string.Format("{0}.{1}", jIt.JoinTable.Value.Caption, "status"), "","");
                                    }
                                    else
                                    {
                                        this.AddOutFieldKey("record_id", string.Format("{0}.{1}", jIt.JoinTable.TableName, "record_id"), string.Format("{0}.{1}", jIt.JoinTable.Value.Caption, "record_id"), "","");
                                        this.AddOutFieldKey("parent_id", string.Format("{0}.{1}", jIt.JoinTable.TableName, "parent_id"), string.Format("{0}.{1}", jIt.JoinTable.Value.Caption, "parent_id"), "","");
                                        this.AddOutFieldKey("sort_id", string.Format("{0}.{1}", jIt.JoinTable.TableName, "sort_id"), string.Format("{0}.{1}", jIt.JoinTable.Value.Caption, "sort_id"), "", "");
                                        this.AddOutFieldKey("status", string.Format("{0}.{1}", jIt.JoinTable.TableName, "status"), string.Format("{0}.{1}", jIt.JoinTable.Value.Caption, "status"), "","");
                                    }
                                    foreach (BillSourceFields field in jIt.JoinTable.Value.Fields)
                                    {
                                        this.AddOutFieldKey(field.Key, string.Format("{0}.{1}",jIt.JoinTable.TableName,field.Key), string.Format("{0}.{1}", jIt.JoinTable.Value.Caption, field.Caption), field.LanguageTexts,field.Caption);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            this.RepositoryOutFieldEdit.Items.Clear();
            if (this.outList.Count > 0)
            {
                foreach (OutFieldData field in outList)
                {
                    this.RepositoryOutFieldEdit.Items.Add(field);
                }
            }

        }
        /// <summary>
        /// 添加字段到输出字段
        /// </summary>
        /// <param name="key">字段名</param>
        /// <param name="keyPath">带表名的字段</param>
        /// <param name="caption">路径</param>
        /// <param name="language">多语言</param>
        /// <param name="shortCaption">字段名</param>
        private void AddOutFieldKey(string key, string keyPath, string caption, string language,string shortCaption)
        {
            if (outList.Count > 0)
            {
                bool exists = false;
                for (int i = 0; i < outList.Count; i++)
                {
                    OutFieldData data = outList[i];
                    if (data.Key == key)
                    {
                        exists = true;
                        break;
                    }
                }
                if (!exists)
                {
                    OutFieldData data = new OutFieldData(key, keyPath, caption, language,shortCaption);
                    outList.Add(data);
                }
                else
                {
                    key = string.Format("{0}_key", key);
                    this.AddOutFieldKey(key, keyPath, caption, language, shortCaption);
                }
            }
            else
            {
                OutFieldData data = new OutFieldData(key, keyPath, caption, language, shortCaption);
                outList.Add(data);
            }
        }

        /// <summary>
        /// 为目录列表加载模块配置bean
        /// </summary>
        /// <returns></returns>
        private bool LoadFormatBean()
        {
            string billName = ""; int ModType = ProjectUtil.TYPE_BILL_MODULE;
            ImageListBoxItem check = null;
            if (IListBox.Items.Count > 0)
            {
                for (int i = 0; i < IListBox.Items.Count; i++)
                {
                    ImageListBoxItem item = IListBox.Items[i];
                    if (item.ImageIndex == 4)
                    {
                        check = item;
                        billName = (string)item.Value;
                        if (item.Description.IndexOf("单据") == -1)
                        {
                            ModType = ProjectUtil.TYPE_DIC_MODULE;
                        }
                        break;
                    }
                }
            }
            if (check != null && billName != "")
            {
                loadBillName = billName;
                loadBillType = ModType;
                bool ReadOnly = false;
                RootPanel.Http.AsyncResourcesXmlBean(billName, "", ModType, ref ReadOnly, null, LoadXml);
                return true;
            }
            else
            {
                return false;
            }

        }

        /// <summary>
        /// xml转bean
        /// </summary>
        /// <param name="key"></param>
        /// <param name="xml"></param>
        private void LoadXmlToThreed(string key, string xml)
        {
            bool success = true;
            BillFormatModule loadBill = null;
            if (key == "OK")
            {
                XmlDocument XmlDoc = new XmlDocument();
                try
                {
                    XmlDoc.LoadXml(xml);
                    if (this.loadBillType == ProjectUtil.TYPE_BILL_MODULE)//加载单据
                    {
                        JAXBContext<BillModuleItem> jaxb = new JAXBContext<BillModuleItem>();
                        try
                        {
                            BillModuleItem bean = jaxb.unmarshal(XmlDoc.OuterXml);
                            loadMod.Add(bean);
                            loadBill = bean;
                        }
                        catch (Exception ex)
                        {
                            logger.Error("XMLTOBean失败", ex);
                            success = false;
                        }
                    }
                    else if (this.loadBillType == ProjectUtil.TYPE_DIC_MODULE)//加载字典
                    {

                    }

                }
                catch (Exception ex)
                {
                    logger.Error("返回Xml格式化失败:" + ex.Message, ex);
                    success = false;

                }
            }
            else
            {
                success = false;
            }

            //标记加载结果
            if (IListBox.Items.Count > 0)
            {
                for (int i = 0; i < IListBox.Items.Count; i++)
                {
                    ImageListBoxItem item = IListBox.Items[i];
                    if (item.Value.Equals(this.loadBillName))
                    {
                        int index = success ? 3 : 10;
                        item.ImageIndex = index;
                        if (loadBill != null) item.Tag = loadBill;
                        break;
                    }
                }
            }


            if (!LoadFormatBean())
            {
                this.connect = false;
            }
        }


        public void AddParamGridRow(string key, string caption, string column)
        {
            DataRow Row = reqData.NewRow();
            Row["FieldParamKey"] = key;
            Row["FieldReqCaption"] = caption;
            Row["FieldReqValue"] = column;
            reqData.Rows.Add(Row);
            GridReqView.RefreshData();
        }

        /// <summary>
        /// 加载服务器异步回调方法转界面线程 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadXml(object sender, PropertyDataEvent e)
        {
            //异步转同步
            this.BeginInvoke(new UpdateStatusDelegate(LoadXmlToThreed), new object[] { e.Key, (string)e.Value });
            
        }

        #region 界面移动控制



        private bool isMouseDown = false;
        private Point FormLocation;     //form的location
        private Point mouseOffset;      //鼠标的按下位置

        private void BoxPanel_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = true;
                FormLocation = this.Location;
                mouseOffset = Control.MousePosition;
            }
        }

        private void BoxPanel_MouseMove(object sender, MouseEventArgs e)
        {
            int _x = 0;
            int _y = 0;
            if (isMouseDown)
            {
                Point pt = Control.MousePosition;
                _x = mouseOffset.X - pt.X;
                _y = mouseOffset.Y - pt.Y;

                this.Location = new Point(FormLocation.X - _x, FormLocation.Y - _y);
            }
        }

        private void BoxPanel_MouseUp(object sender, MouseEventArgs e)
        {
            isMouseDown = false;
        }

        #endregion

        /// <summary>
        /// 加载选择模块配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnLoadTable_Click(object sender, System.EventArgs e)
        {
            if (!this.connect)
            {
                this.connect = true;
                LoadFormatBean();
            }
            else
            {
                RootPanel.ShowAlert("提示:", "当前正加载数据，请稍后再操作");
            }
        }
        /// <summary>
        /// 选择已加载的目录结构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSelectMod_Click(object sender, System.EventArgs e)
        {
            AutoQuerySelect Form = new AutoQuerySelect(RootPanel);
            DialogResult DR = Form.ShowDialog();
            if (DR == DialogResult.OK && Form.FormatModList.Count > 0)
            {
                //new DevExpress.XtraEditors.Controls.ImageListBoxItem("Custmeor", "外销合同", 4)
                for (int i = 0; i < Form.FormatModList.Count; i++)
                {
                    SelectItem item = Form.FormatModList[i];
                    ImageListBoxItem image = new ImageListBoxItem(item.Key, item.ToString(), 4);
                    IListBox.Items.Add(image);
                }
            }
        }

        private void IListBox_DoubleClick(object sender, System.EventArgs e)
        {

            ImageListBoxItem item = (ImageListBoxItem)IListBox.SelectedItem;
            if (item.ImageIndex == 3 && item.Tag is BillFormatModule)
            {
                bool ExistAdd = false;
                BillFormatModule bill = (BillFormatModule)item.Tag;
                if (bill.getBillType() == ProjectUtil.TYPE_BILL_MODULE || bill.getBillType() == ProjectUtil.TYPE_BILL_MULTIPLE)
                {
                    #region 单据
                    BillModuleItem billMod = (BillModuleItem)bill;
                    AutoQueryCheckForm CHeckForm = new AutoQueryCheckForm(billMod, RootPanel, this);
                    DialogResult DR = CHeckForm.ShowDialog();
                    if (DR == DialogResult.OK)
                    {
                        List<string> list = CHeckForm.CheckList;
                        if (list.Count > 0)
                        {
                            foreach (string caption in list)
                            {
                                bool exists = false;
                                //判断是否重复
                                foreach (DataRow Row in TableData.Rows)
                                {
                                    if (caption == (string)Row["TabNameCol"])
                                    {
                                        exists = true;
                                        break;
                                    }
                                }

                                if (!exists)
                                {
                                    BillSourceTabItems tabItem = null;
                                    //查询数据源
                                    if (billMod.DataSource != null && billMod.DataSource.TableItems != null && billMod.DataSource.TableItems.Count > 0)
                                    {
                                        foreach (BillSourceTabItems source in billMod.DataSource.TableItems)
                                        {
                                            if (source.Caption == caption)
                                            {
                                                tabItem = source;
                                                break;
                                            }
                                        }
                                    }
                                    if (tabItem != null)
                                    {
                                        SelectItem select = new SelectItem(billMod, tabItem, tabItem.Caption);
                                        select.HasRole = tabItem.Key == "0";
                                        DataRow row = TableData.NewRow();
                                        row["TabNameCol"] = tabItem.Caption;
                                        row["TabRoleCol"] = select.HasRole;
                                        row["TabSourceKey"] = billMod.getKey();
                                        row["TabGroupValue"] = select;
                                        TableData.Rows.Add(row);
                                        TargetSelect.Add(select);
                                        ExistAdd = true;
                                    }
                                }
                            }
                        }

                    }
                    #endregion
                }
                else //当前是字典
                {
                    bool exists = false;
                    //判断是否重复
                    foreach (DataRow Row in TableData.Rows)
                    {
                        if (bill.getCaption() == (string)Row["TabNameCol"])
                        {
                            exists = true;
                            break;
                        }
                    }
                    if (!exists)
                    {
                        BillSourceTabItems tabItem = null;
                        //查询数据源
                        if (bill.DataSource != null && bill.DataSource.TableItems != null && bill.DataSource.TableItems.Count > 0)
                        {
                            tabItem = bill.DataSource.TableItems[0];
                        }
                        if (tabItem != null)
                        {
                            SelectItem select = new SelectItem(bill, tabItem, tabItem.Caption);
                            DataRow row = TableData.NewRow();
                            row["TabNameCol"] = bill.getCaption();
                            row["TabRoleCol"] = true;
                            row["TabSourceKey"] = bill.getKey();
                            row["TabGroupValue"] = select;
                            TableData.Rows.Add(row);
                            TargetSelect.Add(select);
                            ExistAdd = true;
                        }
                    }
                }

                if (ExistAdd)
                {
                    GridTableView.RefreshData();
                    this.LoadWillJoinGridData();
                    this.LoadJoinGirdData();
                    this.LoadOutFieldListData();
                }
            }
        }


        private void GridTableView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle >= 0)
            {
                DataRow Row = TableData.Rows[e.FocusedRowHandle];
                SelectItem item = (SelectItem)Row["TabGroupValue"];
                if (!item.MainTable)
                {
                    GridTableView.OptionsBehavior.Editable = false;
                }
                else
                {
                    GridTableView.OptionsBehavior.Editable = true;
                }
            }

        }

        private void WhSqlMemo_EditValueChanged(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 外联行控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void groupControl4_CustomButtonClick(object sender, DevExpress.XtraBars.Docking2010.BaseButtonEventArgs e)
        {
            if (Convert.ToString(e.Button.Properties.Tag) == "Add")
            {
                DataRow Row = JoinData.NewRow();
                Row["FieldWillJoinTable"] = "";
                Row["FieldJoinType"] = "";
                Row["FieldJoinTable"] = "";
                Row["FieldJoinObject"] = new SelectJoinItem();
                JoinData.Rows.Add(Row);
                GridJoinView.RefreshData();
                GridJoinView.MoveLast();
            }
            else if (Convert.ToString(e.Button.Properties.Tag) == "Delete")
            {
                if (GridJoinView.FocusedRowHandle >= 0)
                {
                    DataRow Row = JoinData.Rows[GridJoinView.FocusedRowHandle];
                    SelectJoinItem join = (SelectJoinItem)Row["FieldJoinObject"];
                    if (join.ParentTable != null)
                    {
                        join.ParentTable.JoinList.Remove(join);
                        join.ParentTable = null;
                    }
                    Row["FieldJoinObject"] = null;
                    JoinData.Rows.RemoveAt(GridJoinView.FocusedRowHandle);
                    GridJoinView.RefreshData();
                }
            }

        }

        private void groupControl2_CustomButtonClick(object sender, DevExpress.XtraBars.Docking2010.BaseButtonEventArgs e)
        {
            MessageBox.Show(e.Button.Properties.Tag.ToString());
        }

        /// <summary>
        /// Join表字段内容改变修改属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridJoinView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                DataRow Row = JoinData.Rows[e.RowHandle];
                SelectJoinItem join = (SelectJoinItem)Row["FieldJoinObject"];
                string JoinTable = Convert.ToString(Row["FieldJoinTable"]);
                string JoinType = Convert.ToString(Row["FieldJoinType"]);
                string WillTable = Convert.ToString(Row["FieldWillJoinTable"]);
                join.JoinType = JoinType;
                if (join.JoinTable == null) join.JoinTable = new SelectItem();
                //查询joinTable信息
                BillFormatModule Mod = null; BillSourceTabItems SouTab = null;

                foreach (BillFormatModule bill in loadMod)
                {
                    if (bill.DataSource != null && bill.DataSource.TableItems != null && bill.DataSource.TableItems.Count > 0)
                    {
                        foreach (BillSourceTabItems source in bill.DataSource.TableItems)
                        {
                            if (source.Caption == JoinTable)
                            {
                                SouTab = source;
                                break;
                            }
                        }
                    }
                    if (SouTab != null)
                    {
                        Mod = bill;
                    }
                }
                if (SouTab != null)
                {
                    join.JoinTable.Bill = Mod;
                    join.JoinTable.Value = SouTab;
                    join.JoinTable.Key = Mod.getKey();
                    join.JoinTable.Caption = SouTab.Caption;
                    join.JoinTable.ModType = Mod.getBillType();
                    join.JoinTable.MainTable = SouTab.Key == "0";
                    join.JoinTable.TableName = SouTab.TableName;
                }

                //查询所属WillTable信息
                SelectItem WillSelect = null;
                foreach (SelectItem it in TargetSelect)
                {
                    if (it.Caption == WillTable)
                    {
                        WillSelect = it;
                        break;
                    }
                }
                if (WillSelect != null)
                {
                    if (join.ParentTable != null && join.ParentTable != WillSelect)
                    {
                        join.ParentTable.JoinList.Remove(join);
                        join.ParentTable = null;
                    }

                    if (!WillSelect.JoinList.Contains(join))
                    {
                        WillSelect.JoinList.Add(join);
                        join.ParentTable = WillSelect;
                    }
                }
                else
                {
                    if (join.ParentTable != null)
                    {
                        join.ParentTable.JoinList.Remove(join);
                        join.ParentTable = null;
                    }
                }

                this.LoadOutFieldListData();
            }

        }

        private void GridJoinView_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                //JoinRowOld = JoinData.NewRow();
                //JoinRowOld["FieldWillJoinTable"] = JoinData.Rows[e.RowHandle]["FieldWillJoinTable"];
                //JoinRowOld["FieldJoinType"] = JoinData.Rows[e.RowHandle]["FieldJoinType"];
                //JoinRowOld["FieldJoinTable"] = JoinData.Rows[e.RowHandle]["FieldJoinTable"];
                //JoinRowOld["FieldWillJoinTable"] = null;
            }
        }

        //private DataRow JoinRowOld = null;

        /// <summary>
        /// join表行改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridJoinView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle >= 0)
            {
                DataRow Row = JoinData.Rows[e.FocusedRowHandle];
                SelectJoinItem join = (SelectJoinItem)Row["FieldJoinObject"];
                JoinWSqlMemo.Text = join.Content;
            }
        }

        private void JoinWSqlMemo_KeyUp(object sender, KeyEventArgs e)
        {
            int Handle = GridJoinView.FocusedRowHandle;
            if (Handle >= 0)
            {
                DataRow Row = JoinData.Rows[Handle];
                SelectJoinItem join = (SelectJoinItem)Row["FieldJoinObject"];
                join.Content = JoinWSqlMemo.Text;
            }
            else
            {
                JoinWSqlMemo.Text = "";
            }
        }
        private void JoinWSqlMemo_TextChanged(object sender, EventArgs e)
        {
            int Handle = GridJoinView.FocusedRowHandle;
            if (Handle >= 0)
            {
                DataRow Row = JoinData.Rows[Handle];
                SelectJoinItem join = (SelectJoinItem)Row["FieldJoinObject"];
                join.Content = JoinWSqlMemo.Text;
            }
            else
            {
                JoinWSqlMemo.Text = "";
            }
        }

        /// <summary>
        /// join弹出条件选择框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void groupControl5_CustomButtonClick(object sender, DevExpress.XtraBars.Docking2010.BaseButtonEventArgs e)
        {
            if (GridJoinView.FocusedRowHandle >= 0)
            {
                DataRow Row = JoinData.Rows[GridJoinView.FocusedRowHandle];
                SelectJoinItem join = (SelectJoinItem)Row["FieldJoinObject"];

                List<SelectItem> list = new List<SelectItem>();
                if (join.JoinTable != null)
                {
                    list.Add(join.JoinTable);
                    if (join.ParentTable != null)
                    {
                        list.Add(join.ParentTable);
                    }
                }
                if (expForm == null) expForm = new AutoQueryExpForm(module, this);
                expForm.RegeditDemo(list, JoinWSqlMemo);
                expForm.ShowDialog();
            }

        }


        private AutoQueryExpForm expForm = null;

        public string SqlContent
        {
            get
            {
                return sqlContent;
            }

            set
            {
                sqlContent = value;
            }
        }

        public List<BillFormatModule> LoadMod
        {
            get
            {
                return loadMod;
            }

            set
            {
                loadMod = value;
            }
        }

        public DataTable ReqData
        {
            get
            {
                return reqData;
            }

            set
            {
                reqData = value;
            }
        }

        public List<OutFieldData> OutList
        {
            get
            {
                return outList;
            }

            set
            {
                outList = value;
            }
        }

        public DataTable OutData
        {
            get
            {
                return outData;
            }

            set
            {
                outData = value;
            }
        }

        private void AutoQueryFormula_MouseClick(object sender, MouseEventArgs e)
        {
            RootPanel.AddConsoleText("点击了窗体", false);
        }
        /// <summary>
        /// 条件页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void groupControl6_CustomButtonClick(object sender, DevExpress.XtraBars.Docking2010.BaseButtonEventArgs e)
        {
            if (expForm == null) expForm = new AutoQueryExpForm(module, this);
            expForm.RegeditDemo(TargetSelect, WhSqlMemo);
            DialogResult DR = expForm.ShowDialog();

        }
        /// <summary>
        /// 删除参数行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GroupReqPanel_CustomButtonClick(object sender, DevExpress.XtraBars.Docking2010.BaseButtonEventArgs e)
        {
            if (GridReqView.FocusedRowHandle >= 0)
            {
                reqData.Rows.RemoveAt(GridReqView.FocusedRowHandle);
                GridReqView.RefreshData();
            }
        }
        /// <summary>
        /// 输出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OutGroupPanel_CustomButtonClick(object sender, DevExpress.XtraBars.Docking2010.BaseButtonEventArgs e)
        {
            if (e.Button.Properties.Tag.ToString() == "Add")
            {
                DataRow Row = outData.NewRow();
                Row["ColFieldName"] = null;
                Row["ColWriteField"] = null;
                Row["ColVisible"] = true;
                Row["ColFieldWidth"] = 100;
                Row["ColCommand"] = "";
                Row["ColShowSearch"] = true;
                outData.Rows.Add(Row);
                GridOutView.RefreshData();
            }
            else if (e.Button.Properties.Tag.ToString() == "Delete")
            {
                if (GridOutView.FocusedRowHandle >= 0)
                {
                    outData.Rows.RemoveAt(GridOutView.FocusedRowHandle);
                    GridOutView.RefreshData();
                }
            }
            else if (e.Button.Properties.Tag.ToString() == "Auto")
            {
                if (outList.Count > 0)
                {
                    outData.Rows.Clear();
                    foreach(OutFieldData field in outList)
                    {
                        foreach(OutFieldData thisField in SelfList)
                        {
                            if(field.ShortCaption == thisField.ShortCaption)
                            {
                                DataRow Row = outData.NewRow();
                                Row["ColFieldName"] = field;
                                Row["ColWriteField"] = thisField;
                                Row["ColVisible"] = true;
                                Row["ColFieldWidth"] = 100;
                                Row["ColCommand"] = "";
                                Row["ColShowSearch"] = true;
                                outData.Rows.Add(Row);
                                break;
                            }
                        }
                    }
                    GridOutView.RefreshData();
                }
            }
        }
        /// <summary>
        /// 表数据源修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridTableView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            //TableData = new DataTable("TableName");
            //TableData.Columns.Add("TabNameCol", typeof(string));//表结构caption
            //TableData.Columns.Add("TabRoleCol", typeof(bool));//是否启用权限
            //TableData.Columns.Add("TabSourceKey", typeof(string));//key
            //TableData.Columns.Add("TabGroupValue", typeof(SelectItem));//模块
            if (e.RowHandle >=0 && e.Column.FieldName == "TabRoleCol")
            {
                DataRow Row = TableData.Rows[e.RowHandle];
                SelectItem item = (SelectItem)Row["TabGroupValue"];
                item.HasRole = (bool)Row["TabRoleCol"];
            }
        }

        /// <summary>
        /// 生成SQL语句
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            List<string> groupBy = new List<string>();
            bool hasCommond = false;
            System.Text.StringBuilder sql = new System.Text.StringBuilder();
            sql.Append("select ");
            if (outData.Rows.Count > 0)
            {
                int number = 0;
                foreach(DataRow data in outData.Rows)
                {
                    if (number > 0) sql.Append(",");
                    OutFieldData OutField = (OutFieldData)data["ColFieldName"];
                    string command = (string)data["ColCommand"];
                    if (command != "")
                    {
                        if(!hasCommond)hasCommond = true;
                        sql.Append(command).Append("(").Append(OutField.KeyPath).Append(") ").Append(OutField.Key).Append(" ");
                    }
                    else
                    {
                        if (hasCommond)
                        {
                            groupBy.Add(OutField.KeyPath);
                        }
                        sql.Append(OutField.KeyPath).Append(" ");
                        if (OutField.KeyPath.IndexOf(OutField.Key) == -1)
                        {
                            sql.Append(OutField.Key);
                        }
                    }
                    number++;
                }
            }
            sql.AppendLine();
            sql.Append("from ");
            if (TableData.Rows.Count > 0)
            {
                int TabRow = 0;
                foreach(DataRow data in TableData.Rows)
                {
                    if (TabRow > 0) sql.Append(",");
                    SelectItem item = (SelectItem)data["TabGroupValue"];
                    sql.Append(item.TableName).Append(" ");
                    //查询外联
                    if (item.JoinList != null && item.JoinList.Count > 0)
                    {
                        foreach(SelectJoinItem join in item.JoinList)
                        {
                            if (join.JoinTable != null)
                            {
                                sql.Append(join.JoinType).Append(" ").Append(join.JoinTable.TableName);
                                sql.Append(" on (").Append(join.Content).Append(")");
                            }
                        }
                    }
                    TabRow++;
                }
            }
            
            
            //where条件
            sql.AppendLine();
            string where = string.Format("where {0}",WhSqlMemo.Text);
            sql.Append(where);
            //添加权限
            if (TargetSelect.Count > 0)
            {
                foreach(SelectItem it in TargetSelect)
                {
                    if (it.MainTable && it.HasRole)
                    {
                        if (where.ToLower().IndexOf("and") != -1)
                        {
                            sql.Append(" and QueryRole(").Append(it.Bill.getKey()).Append(",").Append(it.TableName).Append(") ");
                        }
                        else
                        {
                            sql.Append(" QueryRole(").Append(it.Bill.getKey()).Append(",").Append(it.TableName).Append(") ");
                        }
                    }
                }
            }
            //group by
            if (groupBy.Count > 0)
            {
                sql.AppendLine();
                sql.Append("group by ");
                int groupCout = 0;
                foreach(string group in groupBy)
                {
                    if (groupCout > 0) sql.Append(",");
                    sql.Append(group);
                    groupCout++;
                }
            }
            sqlContent = sql.ToString();
            //logger.Info(sqlContent);
        }


        

        
    }

    /// <summary>
    /// 输出字段集Item
    /// </summary>
    public class OutFieldData
    {
        private string key = "";
        private string keyPath = "";
        private string caption = "";
        private string shortCaption = "";
        private string languageText = "";

        public OutFieldData(string _key, string _kepPath, string _caption, string _language, string _shortCaption)
        {
            this.key = _key;
            this.keyPath = _kepPath;
            this.caption = _caption;
            this.languageText = _language;
            this.shortCaption = _shortCaption;
        }
        /// <summary>
        /// 字段输出key
        /// </summary>
        public string Key
        {
            get
            {
                return key;
            }

            set
            {
                key = value;
            }
        }
        /// <summary>
        /// 字段路径caption
        /// </summary>
        public string Caption
        {
            get
            {
                return caption;
            }

            set
            {
                caption = value;
            }
        }
        /// <summary>
        /// 字段多语言
        /// </summary>
        public string LanguageText
        {
            get
            {
                return languageText;
            }

            set
            {
                languageText = value;
            }
        }

        public string KeyPath
        {
            get
            {
                return keyPath;
            }

            set
            {
                keyPath = value;
            }
        }

        public string ShortCaption
        {
            get
            {
                return shortCaption;
            }

            set
            {
                shortCaption = value;
            }
        }

        public override string ToString()
        {
            return caption;
        }
    }
}